//
//  TodayViewController.m
//  WeddingToday
//
//  Created by Marx on 2017/1/19.
//  Copyright © 2017年 郭静芬. All rights reserved.
//

#import "TodayViewController.h"
#import <NotificationCenter/NotificationCenter.h>
#import "masonry.h"
#import "UIImageView+WebCache.h"
#import "GJFClassifyModel.h"
#import "GJFCollectionTableViewCell.h"
#import "UIView+HF.h"

#define WIDTH [UIScreen mainScreen].bounds.size.width


@interface TodayViewController () <NCWidgetProviding, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UIImageView *imgV;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UIView *bottomView;
@end

@implementation TodayViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.extensionContext.widgetLargestAvailableDisplayMode = NCWidgetDisplayModeExpanded;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
//    BOOL isPortrait = UIDeviceOrientationIsPortrait(orientation);
//    if (isPortrait) {
//        NSLog(@"竖屏");
//    }
//    else {
//        NSLog(@"横屏");
//    }
    
    [self setUpUI];
}

- (NSDictionary *)getDataFromNSUserDefaults {
    NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.neusoft.gou.wedd"];
    NSDictionary *value = [shared valueForKey:@"widget"];
    return value;
}

#pragma mark - 设置界面
- (void)setUpUI {
    NSDictionary *dict = [self getDataFromNSUserDefaults];
    [self collectionView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view).mas_offset(0);
        make.top.mas_equalTo(self.collectionView.mas_bottom).mas_offset(0);
    }];
    
    UIImageView *bannerImg = [[UIImageView alloc] initWithFrame:CGRectMake(15, self.collectionView.bottom + 5, WIDTH / 2 - 30, 300 - self.collectionView.bottom - 25)];
    [bannerImg sd_setImageWithURL:[dict objectForKey:@"image_path"] placeholderImage:[UIImage imageNamed:@"占位图"]];
    bannerImg.contentMode = UIViewContentModeScaleAspectFill;
    bannerImg.userInteractionEnabled = NO;
    bannerImg.clipsToBounds = YES;
    [self.view addSubview:bannerImg];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(bannerImg.right + 10, bannerImg.top + 5, WIDTH - bannerImg.right - 30, bannerImg.height - 10)];
    titleLabel.text = [dict objectForKey:@"title"];
    titleLabel.userInteractionEnabled = NO;
    titleLabel.numberOfLines = 0;
    [self.view addSubview:titleLabel];
}

#pragma mark - 打开App
- (void)openURLContainingAPPWithAction:(NSString *)action {
    //通过extensionContext借助host app调起app
    if (![action isKindOfClass:[NSString class]]) {
        action = @"gotoHome";
    }
    NSString *openUrl = [NSString stringWithFormat:@"WeddingToday://%@", action];
//    NSString *openUrl = [NSString stringWithFormat:@"WeddingToday://action=gotohome-1"];
    [self.extensionContext openURL:[NSURL URLWithString:openUrl] completionHandler:^(BOOL success) {
        NSLog(@"open url result:%d",success);
    }];
}

#pragma mark - 延展，折叠宽度
- (void)widgetActiveDisplayModeDidChange:(NCWidgetDisplayMode)activeDisplayMode withMaximumSize:(CGSize)maxSize {
    if (activeDisplayMode == NCWidgetDisplayModeCompact) {
        self.preferredContentSize = CGSizeMake(WIDTH, 70);
        [UIView animateWithDuration:0.4 animations:^{
            self.collectionView.contentInset = UIEdgeInsetsMake(20, 15, 0, 30);
        }];
    }
    else {
        self.preferredContentSize = CGSizeMake(WIDTH, 300);
        [UIView animateWithDuration:0.4 animations:^{
            self.collectionView.contentInset = UIEdgeInsetsMake(5, 15, 0, 30);
        }];
    }
}

#pragma mark - collectionView协议
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GJFCollectionTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    cell.classifyModel = self.dataArr[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString *action = [NSString stringWithFormat:@"gotoHomePage-%ld", indexPath.item];
    [self openURLContainingAPPWithAction:action];
}

#pragma mark - 懒加载

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((WIDTH - 80) / 4, (WIDTH - 80) / 4);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, ((WIDTH - 80) / 2 + 30)) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        //CollectionView的上、左、下、右距离边缘的大小
        _collectionView.contentInset = UIEdgeInsetsMake(5, 15, 0, 30);
        _collectionView.backgroundColor = [UIColor clearColor];
        //CollectionView垂直和水平的拉条隐藏
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_collectionView];
        
        [_collectionView registerClass:[GJFCollectionTableViewCell class] forCellWithReuseIdentifier:@"collectionCell"];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"ClassifyList" ofType:@"plist"];
        NSArray *dicArr = [NSArray arrayWithContentsOfFile:path];
        _dataArr = [GJFClassifyModel transformWithArr:dicArr];
    }
    return _dataArr;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        [self.view addSubview:_bottomView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openURLContainingAPPWithAction:)];
        [_bottomView addGestureRecognizer:tap];
    }
    return _bottomView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIEdgeInsets)widgetMarginInsetsForProposedMarginInsets:(UIEdgeInsets)defaultMarginInsets {
    return UIEdgeInsetsZero;
}

- (void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
    // Perform any setup necessary in order to update the view.
    
    // If an error is encountered, use NCUpdateResultFailed
    // If there's no update required, use NCUpdateResultNoData
    // If there's an update, use NCUpdateResultNewData

    completionHandler(NCUpdateResultNewData);
}

@end
